<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-row>
        <el-col :span="10">
          <el-button class="filter-item" size="small" style="margin-left: 10px;" type="primary" v-waves
                     @click="showLockStock" icon="el-icon-edit">锁定
          </el-button>
          <el-button class="filter-item" size="small" style="margin-left: 10px;" type="primary" v-waves
                     @click="showUnlockStock" icon="el-icon-edit">解锁
          </el-button>
          <el-button class="filter-item" size="small" style="margin-left: 10px;" type="primary" v-waves
                     @click="updateLocation" icon="el-icon-edit">库位调整
          </el-button>
          <el-button class="filter-item" size="small" style="margin-left: 10px;" type="primary" v-waves
                     @click="handleDownload" :loading="downloadLoading" icon="el-icon-download">导出
          </el-button>
          <el-button class="filter-item" size="small" style="margin-left: 10px;" type="primary" v-waves
                     @click="handleAllDownload" :loading="downloadAllLoading" icon="el-icon-download">导出所有
          </el-button>
        </el-col>
        <el-col :span="14" style="text-align: right">
          <el-input size="small" style="width: 200px" class="filter-item fsc-search" placeholder="车架号"
                    v-model="listQuery.condition.lotNo1" @keyup.enter.native="searchClick"></el-input>
          <!--搜索-->
          <el-button class="filter-item" size="small" type="primary" v-waves icon="el-icon-circle-plus-outline"
                     @click="moreClick">更多
          </el-button>
          <el-dropdown trigger="click" :hide-on-click=false style="float: right;margin-left: 10px">
            <span class="el-dropdown-link">
              <el-button class="filter-item" size="small" type="primary" v-waves>
                选择列
                <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <el-checkbox-group v-model="theadCheckVal">
                  <el-checkbox label="storeHouseName">仓库</el-checkbox>
                  <el-checkbox label="ownerId">客户</el-checkbox>
                  <el-checkbox label="materielId">车型</el-checkbox>
                  <el-checkbox label="lotNo1">车架号</el-checkbox>
                  <el-checkbox label="lotNo2">物料代码</el-checkbox>
                  <el-checkbox label="lotNo3">颜色</el-checkbox>
                  <el-checkbox label="lotNo4">车型代码</el-checkbox>
                  <el-checkbox label="storeAreaName">库区</el-checkbox>
                  <el-checkbox label="locationName">储位</el-checkbox>
                  <el-checkbox label="inboundTime">入库时间</el-checkbox>
                  <el-checkbox label="storeDetail">实车位置</el-checkbox>
                  <el-checkbox label="qty">数量</el-checkbox>
                  <el-checkbox label="stockStatus">状态</el-checkbox>
                  <el-checkbox label="lockTime">锁定原因</el-checkbox>
                  <el-checkbox label="lockReason">锁定时间</el-checkbox>
                  <el-checkbox label="unlockReason">解锁原因</el-checkbox>
                  <el-checkbox label="unlockTime">解锁时间</el-checkbox>
                </el-checkbox-group>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-col>
      </el-row>
      <div style="clean:both"></div>
    </div>
    <div v-show="searchFlag" style="height: auto;margin-top: 10px;">
      <el-form ref="form" :model="listQuery.condition" label-width="80px" :inline="true">
        <el-form-item label=车架号:>
          <el-input type="textarea" :rows="2" style="width: 250px"
                    v-model="listQuery.condition.lotNo1"  placeholder="请输入车架号, 以逗号来分隔"></el-input>
          <!--<el-input placeholder="请输入车架号" class="w200" clearable v-model="listQuery.condition.vinNo"></el-input>-->
        </el-form-item>
        <el-form-item label="货主:">
          <el-input v-model="listQuery.condition.ownerId" size="small" style="width: 200px"
                    class="filter-item more-search" placeholder="请输入货主"></el-input>
        </el-form-item>
        <el-form-item label="车型:">
          <el-input v-model="listQuery.condition.materielId" size="small" style="width: 200px"
                    class="filter-item more-search" placeholder="请输入车型"></el-input>
        </el-form-item>
        <el-form-item label="库位:">
          <el-input v-model="listQuery.condition.locationCode" size="small" style="width: 200px"
                    class="filter-item more-search" placeholder="请输入库位"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="listQuery.condition.stockStatus" placeholder="请选择状态">
            <el-option label="未选择" value=""></el-option>
            <el-option label="正常" value="10"></el-option>
            <el-option label="锁定" value="20"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchClick" style="margin-left: 10px">查询</el-button>
          <el-button type="primary" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div style="clean:both"></div>

    <el-table ref="paymentTable" :data="stockList" v-loading="listLoading"
              element-loading-text="加载中" border fit highlight-current-row
              style="width: 100%;margin-top:5px" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="35"></el-table-column>
      <el-table-column align="center" label="id" v-if="false" width="0">
        <template slot-scope="scope">
          <span>{{scope.row.stockId}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="序号" width="50" fixed="left">
        <template slot-scope="scope">
          <span>{{scope.$index + 1}}</span>
        </template>
      </el-table-column>

      <el-table-column :key="key" align="center" :width="value.width" v-for='(value,key) in tableThead'
                       :label="value.title">
        <template slot-scope="scope">
          <div v-if="value.key === 'stockStatus'">{{scope.row[value.key] | stockStatusFilter}}</div>
          <div v-else>{{scope.row[value.key]}}</div>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page.sync="listQuery.current" :page-sizes="[10,20,30,50]" :page-size="listQuery.size"
                     layout="total, sizes, prev, pager, next, jumper" :total="listQuery.total">
      </el-pagination>
    </div>

    <!--更改库位弹窗-->
    <el-dialog title="更改库位" :visible.sync="dialogVisible" width="35%" :before-close="handleClose">
      <div style="width: 100%;box-sizing: border-box;padding-left: 100px;">
        <el-form ref="form" :model="changeLocation" label-width="100px">
          <el-form-item label="仓库">
            <el-input v-model="changeLocation.storeHouseName" class="w200" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="原库区编码">
            <el-input v-model="changeLocation.oldAreaName" class="w200"  :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="原库位编码">
            <el-input v-model="changeLocation.oldLocationCode" class="w200"  :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="选择调整库区">
            <el-select class="w200" v-model="selectArea.storeAreaId" @change="areasChange" placeholder="请选择库区">
              <el-option v-for="sArea in areaList" :label="sArea.storeAreaName" :value="sArea.storeAreaId"
                         :key="sArea.storeAreaId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择调整库位">
            <el-select class="w200" v-model="selectArea.locationId" placeholder="请选择库位">
              <el-option v-for="sLocation in storeLocationList" :label="sLocation.name" :value="sLocation.id"
                         :key="sLocation.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click='handleClose'>取 消</el-button>
            <el-button class="filter-item" size="small" style="margin-left: 10px;" type="primary"
                       v-waves icon="el-icon-edit" @click="confirmChangeLocation" :disabled="buttonEnable">确 认
            </el-button>
          </el-form-item>
        </el-form>

      </div>
    </el-dialog>
    <!--锁定/解锁弹窗-->
    <el-dialog :title="textMap[lockDialogTitle]" :visible.sync="lockDialogVisible" width="35%" :before-close="handleLockClose">
      <div style="width: 100%;box-sizing: border-box;padding-left: 100px;margin-top: 20px">
        <el-form ref="form" label-width="100px">
          <el-form-item :label="textMap[lockDialogTitle] + '原因'">
            <el-input type="textarea" :rows="4" style="width: 300px"
                      v-model="lockingLocation.reason"  :placeholder="'请输入' + textMap[lockDialogTitle] + '原因'"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click='handleLockClose'>取 消</el-button>
        <el-button class="filter-item" size="small" style="margin-left: 20px;" type="primary"
                   v-waves icon="el-icon-edit" v-if="lockDialogTitle === 'lock'"  @click="lockStock" :disabled="lockingConfirmEnable">确 认
        </el-button>
        <el-button class="filter-item" size="small" style="margin-left: 20px;" type="primary"
                   v-waves icon="el-icon-edit" v-else @click="unlockStock" :disabled="lockingConfirmEnable">确 认
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import * as stockAPI from '@/api/stock/stock'
import waves from '@/directive/waves' // 水波纹指令
const defautlTableThead = [
  { key: 'storeHouseName', title: '仓库', width: '120' },
  { key: 'ownerId', title: '客户', width: '120' },
  { key: 'cusQWaybillNo', title: '客户运单号', width: '120' },
  { key: 'materielId', title: '车型', width: '120' },
  { key: 'lotNo1', title: '车架号', width: 180 },
  { key: 'lotNo2', title: '物料代码', width: '100' },
  { key: 'lotNo3', title: '颜色', width: '' },
  { key: 'lotNo4', title: '车型代码', width: '120' },
  { key: 'storeAreaName', title: '库区', width: '120' },
  { key: 'locationName', title: '储位', width: '120' },
  { key: 'inboundTime', title: '入库时间', width: '120' },
  { key: 'storeDetail', title: '实车位置', width: '120' },
  { key: 'qty', title: '数量', width: '' },
  { key: 'stockStatus', title: '状态', width: '' },
  { key: 'lockReason', title: '锁定原因', width: '' },
  { key: 'lockTime', title: '锁定时间', width: '' },
  { key: 'unlockReason', title: '解锁原因', width: '' },
  { key: 'unlockTime', title: '解锁时间', width: '' }
]
export default {
  name: 'stockQuery',
  directives: {
    waves
  },
  data() {
    return {
      theadCheckVal: [
        'storeHouseName',
        'ownerId',
        'ownerName',
        'materielId',
        'lotNo1',
        'lotNo2',
        'lotNo3',
        'lotNo4',
        'storeAreaName',
        'locationName',
        'inboundTime',
        'storeDetail',
        'qty',
        'stockStatus',
        'lockReason',
        'lockTime',
        'unlockReason',
        'unlockTime'
      ],
      tableThead: defautlTableThead,
      listQuery: {
        current: 1,
        size: 10,
        total: 0,
        condition: {
          storeHouseId: null,
          stockStatus: null,
          ownerId: null,
          locationCode: null,
          materielId: null
        }
      },
      stockList: [],
      listLoading: true,
      searchFlag: false,
      partnerList: [], // 供应商
      companyList: [], // 结算公司
      multipleSelection: [],
      downloadLoading: false,
      dialogVisible: false,
      lockDialogVisible: false,
      buttonEnable: false,
      selectArea: {
        areaId: '',
        locationId: ''
      },
      areaList: [{
        storeLocationList: [],
        storeAreaId: null,
        storeAreaName: null
      }],
      storeLocationList: [],
      changeLocation: {
        storeHouseName: null,
        oldAreaName: null,
        oldLocationId: null,
        oldLocationCode: null,
        newLocationId: null
      },
      downloadAllLoading: false,
      downloadAllData: [],
      lockDialogTitle: '',
      textMap: {
        lock: '锁定',
        unlock: '解锁'
      },
      lockingLocation: {
        stockIds: [],
        reason: null
      },
      lockingConfirmEnable: false
    }
  },
  created() {
    this.list()
  },
  watch: {
    theadCheckVal(valArr) {
      this.tableThead = defautlTableThead.filter(v => {
        for (let i = 0; i < valArr.length; i++) {
          if (v.key === valArr[i]) {
            return v
          }
        }
      })
    }
  },
  methods: {
    list() {
      // 列表查询
      this.listLoading = true
      // 处理是否展开更多
      let queryParam = {}
      if (this.searchFlag) {
        this.listQuery.condition.storeHouseId = this.$store.getters.currentStorehouse.id
        queryParam = this.listQuery
      } else {
        Object.assign(queryParam, this.listQuery)
        queryParam.condition = {
          lotNo1: this.listQuery.condition.lotNo1,
          storeHouseId: this.$store.getters.currentStorehouse.id
        }
      }
      stockAPI.queryStock(queryParam).then(result => {
        if (result.code === 0) {
          this.stockList = result.data.records
          this.listQuery.total = result.data.total
        } else {
          this.$message({
            title: '信息提示',
            message: result.message,
            type: 'error',
            duration: 2000
          })
        }
        this.listLoading = false
      })
    },
    queryAllArea() {
      const queryParam = {}
      queryParam.houseId = this.$store.getters.currentStorehouse.id
      stockAPI.queryAllArea(queryParam).then(result => {
        if (result.code === 0) {
          this.areaList = result.data
        } else {
          this.$message({
            message: result.message,
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    areasChange(val) {
      for (let i = 0; i < this.areaList.length; i++) {
        if (this.areaList[i].storeAreaId === this.selectArea.storeAreaId) {
          this.storeLocationList = this.areaList[i].storeLocationList
          break
        } else {
          this.storeLocationList = []
        }
      }
    },
    // 调整库位
    updateLocation() {
      const that = this
      const selects = that.multipleSelection
      if (selects.length === 0) {
        this.$message({
          title: '错误提示',
          message: '请选择要调整库位的数据',
          type: 'error',
          duration: 2000
        })
      } else if (selects.length > 1) {
        this.$message({
          title: '错误提示',
          message: '仅支持单条数据的库位调整',
          type: 'error',
          duration: 2000
        })
      } else {
        // 请求后台调整
        this.dialogVisible = true
        this.changeLocation.storeHouseName = selects[0].storeHouseName
        this.changeLocation.oldAreaName = selects[0].storeAreaName
        this.changeLocation.oldLocationCode = selects[0].locationCode
        this.queryAllArea()
      }
    },
    confirmChangeLocation() {
      const param = {}
      param.houseId = this.$store.getters.currentStorehouse.id
      param.stockId = this.multipleSelection[0].stockId
      param.newLocationId = this.selectArea.locationId
      this.buttonEnable = true
      stockAPI.updateStockLocation(param).then(response => {
        this.buttonEnable = false
        if (response.code === 0) {
          this.handleClose()
          this.list()
        } else {
          this.$message({
            title: '错误提示',
            message: response.message,
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    // 显示锁定库存弹窗
    showLockStock() {
      const that = this
      if (that.multipleSelection.length) {
        that.lockDialogTitle = 'lock'
        that.lockDialogVisible = true
        that.lockingConfirmEnable = false
        that.lockingLocation = {
          stockIds: [],
          reason: null
        }
        that.multipleSelection.forEach(function(item, index, array) {
          that.lockingLocation.stockIds.push(item.stockId)
        })
      } else {
        that.$message({
          message: '请至少选择一条记录',
          type: 'warning'
        })
      }
    },
    // 锁定库存
    lockStock() {
      const that = this
      that.lockingConfirmEnable = true
      stockAPI.lockStockForBatch(that.lockingLocation).then(response => {
        if (response.code === 0) {
          that.$message({
            title: '成功',
            message: '锁定成功',
            type: 'info',
            duration: 2000
          })
          that.handleLockClose()
          that.list()
        } else {
          that.$message({
            title: '失败',
            type: 'error',
            message: response.message,
            duration: 2000
          })
          that.lockingConfirmEnable = false
        }
      })
    },
    // 显示解锁库存弹窗
    showUnlockStock() {
      const that = this
      if (that.multipleSelection.length) {
        that.lockDialogTitle = 'unlock'
        that.lockDialogVisible = true
        that.lockingConfirmEnable = false
        that.lockingLocation = {
          stockIds: [],
          reason: null
        }
        that.multipleSelection.forEach(function(item, index, array) {
          that.lockingLocation.stockIds.push(item.stockId)
        })
      } else {
        that.$message({
          message: '请至少选择一条记录',
          type: 'warning'
        })
      }
    },
    // 解锁库存
    unlockStock() {
      const that = this
      that.lockingConfirmEnable = true
      stockAPI.unlockStockForBatch(that.lockingLocation).then(response => {
        if (response.code === 0) {
          this.$message({
            title: '成功',
            message: '解锁成功',
            type: 'info',
            duration: 2000
          })
          that.handleLockClose()
          that.list()
        } else {
          this.$message({
            title: '失败',
            type: 'error',
            message: response.message,
            duration: 2000
          })
          that.lockingConfirmEnable = false
        }
      })
    },
    // 库
    handleDownload() {
      if (this.multipleSelection.length) {
        this.downloadLoading = true
        require.ensure([], () => {
          const { export_json_to_excel } = require('@/vendor/Export2Excel')
          const tHeader = ['仓库', '货主', '车型', '车架号', '物料代码']
          const filterVal = ['storeHouseName', 'ownerId', 'materielId', 'lotNo1', 'lotNo2']
          const list = this.multipleSelection
          const data = this.formatJson(filterVal, list)
          this.$refs.paymentTable.clearSelection()
          this.downloadLoading = false
          export_json_to_excel(tHeader, data, this.filename)
        })
      } else {
        this.$message({
          message: '请至少选择一条记录',
          type: 'warning'
        })
      }
    },
    // 库存导出
    handleAllDownload() {
      let queryParam = {}
      queryParam = this.listQuery.condition
      queryParam.storeHouseId = this.$store.getters.currentStorehouse.id
      this.downloadAllLoading = true
      stockAPI.exportStockData(queryParam).then(response => {
        this.downloadAllLoading = false
        if (response.code === 0) {
          this.downloadAllData = response.data
          if (this.downloadAllData.length) {
            const arr = this.changeStatus()
            require.ensure([], () => {
              const { export_json_to_excel } = require('@/vendor/Export2Excel')
              const tHeader = ['客户', '车架号', '车型', '库区', '库位', '状态', '入库时间']
              const filterVal = ['ownerId', 'lotNo1', 'materielId', 'storeAreaName', 'locationName', 'stockStatus', 'inboundTime']
              const data = this.formatJson(filterVal, arr)
              export_json_to_excel(tHeader, data, this.filename)
            })
          }
        } else {
          this.$notify({
            title: '信息提示',
            message: response.message,
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    changeStatus() {
      return this.downloadAllData.map(i => {
        if (!i.stockStatus || i.stockStatus === '10') {
          i.stockStatus = '正常'
        } else if (i.stockStatus === '20') {
          i.stockStatus = '锁定'
        }
        return i
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleSizeChange(val) {
      // 分页size变化
      this.listQuery.size = val
      this.list()
    },
    handleCurrentChange(val) {
      // 分页当前页变化
      this.listQuery.current = val
      this.list()
    },
    moreClick() {
      // 更多click
      this.searchFlag = !this.searchFlag
    },
    searchClick() {
      // 搜索
      this.list()
    },
    handleClose() {
      this.changeLocation = {
        storeHouseName: null,
        oldAreaName: null,
        oldLocationId: null,
        oldLocationCode: null,
        newLocationId: null
      }
      this.areaList = [{
        storeLocationList: [],
        storeAreaId: null,
        storeAreaName: null
      }]
      this.selectArea = {
        areaId: '',
        locationId: ''
      }
      this.storeLocationList = []
      this.dialogVisible = false
      this.list()
    },
    handleLockClose() {
      this.lockingLocation = {
        stockIds: [],
        reason: null
      }
      this.lockDialogVisible = false
      this.list()
    },
    reset() {
      this.listQuery.condition = {
        stockStatus: null,
        ownerId: null,
        locationCode: null,
        materielId: null
      }
      this.list()
    }
  }
}
</script>

